package com.plugin.sproutcore.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;

import com.thoughtworks.xstream.XStream;

public class XStreamUtil 
{
	@SuppressWarnings("unchecked")
	public static <T> T load(File file, Class<T> clazz, String charset) throws IOException {
		Reader reader = null;
		try 
		{
			if (charset != null) {
				reader = new BufferedReader(new InputStreamReader(new 
						FileInputStream(file), charset));
			}
			else
			{
				reader = new BufferedReader(new InputStreamReader(new 
						FileInputStream(file)));
			}
			
			XStream xs = new XStream();
			xs.processAnnotations(clazz);
			return (T)xs.fromXML(reader);
		} 
		finally 
		{
			if (reader != null) {
				reader.close();
			}
		}
	}
	
	public static void save(File file, Object o, String charset) 
	throws IOException 
	{
		BufferedWriter writer = null;
		try 
		{
			writer = new BufferedWriter(new OutputStreamWriter(new 
					FileOutputStream(file), charset));
			
			writer.write("<?xml version=\"1.0\" encoding=\""+charset+"\"?>");
			writer.newLine();
			
			XStream xs = new XStream();
			xs.processAnnotations(o.getClass());
			xs.toXML(o, writer);
		} 
		finally 
		{
			if (writer != null) {
				writer.close();
			}
		}
	}
}
